package com.wyclabs.auth.common.exception;

import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 自定义 oauth2.0 异常的 序列化器
 * @author rs
 * @date 2019/10/17
 */
public class CustomOauth2ExceptionSerializer extends StdSerializer<CustomOauth2Exception> {

    public CustomOauth2ExceptionSerializer() {
        super(CustomOauth2Exception.class);
    }

    @Override
    public void serialize(CustomOauth2Exception e, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        //将状态码设为 200
        HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
        assert response != null;
        response.setStatus(HttpStatus.HTTP_OK);
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("code", e.getErrorCode());
        jsonGenerator.writeStringField("msg", e.getMessage());
        jsonGenerator.writeStringField("data", "");
        jsonGenerator.writeEndObject();
    }
}
